package com.lzb.permanentcalendar.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.lzb.permanentcalendar.BaseAc;
import com.lzb.permanentcalendar.R;
import com.lzb.permanentcalendar.databinding.ActivityCompassBinding;
import com.lzb.permanentcalendar.dialog.PermissionExplainDialog;

import java.util.List;
import java.util.Locale;

public class CompassActivity extends BaseAc<ActivityCompassBinding> implements View.OnClickListener, SensorEventListener {

    private boolean isLock, isShow;
    private float lastRotateDegree;
    private SensorManager sensorManager;
    private long lastUpdateTime = 0;

    @Override
    protected int onCreate() {
        return R.layout.activity_compass;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCompressBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivLock.setOnClickListener(this);
        mDataBinding.tvTzsz.setOnClickListener(this);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //加速度感应器
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        //地磁感应器
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivLock) {//锁定
            isLock = !isLock;
            mDataBinding.ivLock.setImageResource(isLock ? R.drawable.suoding : R.drawable.suo);
        } else if (id == R.id.tvTzsz) {//天子十字
            isShow = !isShow;
            mDataBinding.ivShizi.setVisibility(isShow ? View.VISIBLE : View.GONE);
            if (isShow) {
                mDataBinding.tvTzsz.setBackgroundResource(R.drawable.compress_sz_sel);
                mDataBinding.tvTzsz.setTextColor(Color.parseColor("#FFFFFF"));
            } else {
                mDataBinding.tvTzsz.setBackgroundResource(R.drawable.compress_sz_bg);
                mDataBinding.tvTzsz.setTextColor(Color.parseColor("#AD2419"));
            }
        }
    }

    @Override
    protected void initData() {

    }

    float[] accelerometerValues = new float[3];

    float[] magneticValues = new float[3];

    @Override
    public void onSensorChanged(SensorEvent event) {
        // 判断当前是加速度感应器还是地磁感应器
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            //赋值调用clone方法
            accelerometerValues = event.values.clone();
        } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            //赋值调用clone方法
            magneticValues = event.values.clone();
        }
        if (accelerometerValues != null && magneticValues != null) {
            long curTime = System.currentTimeMillis();
            if (curTime - lastUpdateTime < 500) return;
            lastUpdateTime = curTime;
            if (!isLock) {
                calculateOrientation(); // 加速度和磁场强度两个都有了，才能计算磁极的方向
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    //计算方位
    private void calculateOrientation() {
        float[] R = new float[9];
        float[] values = new float[3];
        SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
        sensorManager.getOrientation(R, values);
        //values[0]的取值范围是-180到180度。
        double value = Math.toDegrees(values[0]);
        //+-180表示正南方向，0度表示正北，-90表示正西，+90表示正东
        if ((value >= 170 && value <= 180) || value >= -180 && value < -170) {

        } else if (value >= 80 && value <= 100) {

        } else if (value >= 100 && value < 170) {

        } else if (value >= 10 && value < 80) {

        } else if (value >= -100 && value < -80) {

        } else if (value >= -170 && value < -100) {

        } else if (value >= -80 && value < -10) {

        } else if (value >= -10 && value < 10) {

        }
        getSeatAndFace((float) (value < 0 ? value + 360 : value));
        mDataBinding.tvCompassJd.setText(String.format("%.1f", value < 0 ? value + 360 : value) + getString(com.lzb.permanentcalendar.R.string.unit_angle));
        //将计算出的旋转角度取反，用于旋转指南针背景图
        float rotateDegree = -(float) value;
        if (Math.abs(rotateDegree - lastRotateDegree) > 1) {
            RotateAnimation animation = new RotateAnimation(lastRotateDegree, rotateDegree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setFillAfter(true);
            mDataBinding.ivCompassZz.startAnimation(animation); //动画效果转动传感器
            lastRotateDegree = rotateDegree;
        }
    }

    /**
     * 把 0-360° 方位角 → 中文 8 方位
     */
    private void getSeatAndFace(float azimuth360) {
        // 8 方位：北、东北、东、东南、南、西南、西、西北
        String[] dirs = {"北", "东北", "东", "东南", "南", "西南", "西", "西北"};
        // 每 45° 一个区间
        int index = Math.round(azimuth360 / 45f) & 7;
        String face = dirs[index];          // 手机正面朝向
        String back = dirs[(index + 4) & 7]; // 背面 = 坐向
        mDataBinding.tvZuo.setText(back);
        mDataBinding.tvXiang.setText(face);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sensorManager != null) {
            sensorManager.unregisterListener(this);
        }
    }

}